from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime
from MMap.models import User, Connection, PHash, Message, Block

def login(request):
	 if request.session.get('user') != None:
		return HttpResponseRedirect('/')
	 if request.method == 'GET':
	 	return render_to_response('login.html')	
	 	
	 if request.method == 'POST':
	 	username = request.POST['username']
		clearPass = request.POST['password']
	 	password = PHash().encode(request.POST['password'])
	 	myLatitude = float(request.POST['latitude'])
	 	myLongitude = float(request.POST['longitude'])
	 		
	 	error = 'Please enter a username and password.'
	 	if len(username.strip()) == 0:
	 		return render_to_response('login.html',{'error_message': error})
	 	if len(username.strip()) < 4:
	 		error = 'Please enter a username longer than 3 characters.'
			return render_to_response('login.html',{'error_message': error})		
		if password == PHash().encode(''):
	 		return render_to_response('login.html',{'error_message': error})
	 	error = 'Incorrect username or password.'
	 	try:
	 		myUser = User.objects.get(name=username)
	 	except:
	 		return render_to_response('login.html',{'error_message': error})
        
		if myUser and myUser.password == password:#clearPass:
			myUser.latitude = myLatitude;
			myUser.longitude = myLongitude;
        		request.session['user'] = myUser
    			myUser.status = 1
    			myUser.save()
			return HttpResponseRedirect('/')
		else:
    			return render_to_response('login.html',{'error_message':error, 'user':username})
    				
def register(request): 	
	 
	 if request.method == 'GET':
	 	return render_to_response('login.html')	
	 	
	 if request.method == 'POST':
	 	username = request.POST['username']
	 	password = PHash().encode(request.POST['password'])
	 	myLatitude = request.POST['latitude']
	 	myLongitude = request.POST['longitude']
	 		
	 	error = 'Please enter a username and password.'
	 	if len(username.strip()) == 0:
	 		return render_to_response('login.html',{'error_message': error})
		if len(username.strip()) < 4:
			error = 'Please enter a username longer than 3 characters.'
	 		return render_to_response('login.html',{'error_message': error})
	 	if password == PHash().encode(''):
	 		return render_to_response('login.html',{'error_message': error})
	 	try:
	 		myUser = User.objects.get(name=username)
	 		error = 'The username you entered already exists.'
 			return render_to_response('login.html',{'error_message': error})
	 	except:
	    		myUser = User(name = username, password = password, status = 1, latitude = myLatitude, longitude = myLongitude)
    			myUser.save()
    			request.session['user'] = myUser;
    			return HttpResponseRedirect('/')
    		
def logout(request):
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	user = request.session['user']
	user.status = 0
	user.save()
#	request.session.clear()
	request.session.flush()
	return HttpResponseRedirect('/login')

def connectionList(request, source):
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	connection_list = Connection.objects.filter(source=source)
	sourceUser = User.objects.get(id=source)
	return render_to_response('connection.html',{'source':sourceUser, 'connections':connection_list})

def connectionIndex(request):	
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
#	return HttpResponse("Hello, world. You're at the connection index.")
	connection_list = Connection.objects.all()
	return render_to_response('connection.html',{'connections':connection_list})

def userIndex(request):	
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	sessionUser = request.session.get('user')
	friends = friendList(sessionUser)
	user_list = User.objects.all()
	return render_to_response('user.html',{'users':user_list, 'sessionUser':sessionUser, 'friends':friends})

def addUser(request):	
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	if request.method == 'POST':
		src = request.session.get('user')
		for key, value  in request.POST.iteritems():
			targ_id = value
			try:
				targ = User.objects.get(id=targ_id)
			except:
				continue
			if src == targ:
				continue
			conn = Connection(source=src, target=targ)
			conn.save()
		
		return HttpResponseRedirect('/friends')
	return HttpResponseRedirect('/')		

def delete(request, target):
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	src = request.session.get('user')
	trg = User.objects.get(name=target)
	conn = Connection.objects.get(source=src, target=trg)
	if request.method == 'GET':
		return render_to_response('delete.html', {'connection':conn})
	if request.method == 'POST':
		conn.delete()
		return HttpResponseRedirect('/friends/')

def showMap(request):
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	user = request.session.get('user')
	sensorParam = 'true'
	user_list = User.objects.filter(status=1)
	friend_list = friendList(user)	
	return render_to_response('map.html',{'sensorParam':sensorParam,'user':user, 'users':user_list, 'friends':friend_list})

def centerMap(request, target):	
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	user = request.session.get('user')
	sensorParam = 'true'
	user_list = User.objects.filter(status=1)
	friend_list = friendList(user)	
	trg = User.objects.get(name=target)
	if trg.status == 0:
		trg = None
	return render_to_response('map.html',{'sensorParam':sensorParam,'user':user, 'users':user_list, 'friends':friend_list, 'target':trg})


def friendList(user):
	connection_list = Connection.objects.filter(source=user)
	friend_list = []
	for conn in connection_list:
		friend_list.append(conn.target)

	return friend_list

@csrf_exempt
def mapRefresh(request):
	if request.session.get('user') == None:
		return HttpResponse('')
	user = request.session.get('user')
	user.latitude=request.POST['latitude']
	user.longitude=request.POST['longitude']
	user.save()
	return HttpResponse(usersToString(request))

def usersToString(request):
	user_list = User.objects.filter(status=1)
	allUsers = ''
	user = request.session.get('user')
	friends = friendList(user)
        for user in user_list:
                userStr = user.name+','
		userStr += str(user.latitude)+','
                userStr += str(user.longitude)+','
		if user in friends:
			userStr+= 'true'
		else:
			userStr+= 'false'
		allUsers += userStr+'|'
	return allUsers;

def friends(request):	
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	user = request.session.get('user')
	friend_list = Connection.objects.filter(source=user)
	follower_list = Connection.objects.filter(target=user)
	messages = Message.objects.filter(target=user, read=False)
	return render_to_response('friends.html', {'friends':friend_list, 'sessionUser':user, 'followerCount':len(follower_list),'new_messages':len(messages)} )

def chat(request, target):
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	user = request.session.get('user')
	trg = User.objects.get(name=target)
	messages = Message.objects.order_by('timestamp').filter(source__in=[user, trg],target__in=[user,trg])
	markAsRead(messages)
	return render_to_response('chat.html', {'messages':messages, 'sessionUser':user, "target":trg})

def inbox(request):
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	user = request.session.get('user')
	all_messages = Message.objects.filter(target=user, read=False)
	markAsRead(all_messages)
	return render_to_response('inbox.html', {'messages':all_messages})

def markAsRead(messages):
	for msg in messages:
		msg.read = True
		msg.save()
		
@csrf_exempt
def saveMessage(request, target):
	if request.session.get('user') == None:
		return HttpResponse('<font color=red>You are not logged in </font></br>')
	user = request.session.get('user')
	if request.method == 'POST':
		try:
			msgText = request.POST['text']
			trg = User.objects.get(name=target)
			msg = Message(source=user, target=trg, text=msgText, timestamp=datetime.now().strftime('%I:%M:%S %p'))
			msg.save()
		except:
			return HttpResponse('<p><font color=red>error sending message</font></p>')
	return HttpResponse(user.name+' ('+msg.timestamp+'): '+msg.text+'<br/>')

def newMessages(request, target):
	if request.session.get('user') == None:
		return HttpResponseRedirect('/login')
	user = request.session.get('user')
	trg = User.objects.get(name=target)
	messages = Message.objects.filter(source=trg, read=False)
	response = ''
	for msg in messages:
		response = msg.source.name+' ('+msg.timestamp+'): '+msg.text+'<br/>'
		msg.read = True
		msg.save()
	return HttpResponse(response)
